#include "filesystem.h"
#include<QDateTime>
#include <QDebug>
#include <QFile>

FileSystem::FileSystem()
{
    root_dir = QDir(QDir(QDir::currentPath()).absolutePath()+"/Data");
    root_dir.mkpath(root_dir.absolutePath());
}

bool FileSystem::save_file(const QList<double>& pixel, const QList<double>& voltage,const QString& gain, const QString& inter_time, const QString& ids)
{
    QDir file_dir = QDir(root_dir.absolutePath()+"/"+get_curr_date_dir()+"/"+ids+"/");

    bool mkpath_ok = file_dir.mkpath(file_dir.absolutePath());
    if(!mkpath_ok){ return false;qDebug()<<0;}

    QDir::setCurrent(file_dir.absolutePath());

    QFile file(get_curr_time_fn()+ids+file_ext);
    if(file.open(QIODevice::WriteOnly | QIODevice::Text))
    {
        QTextStream out(&file);
        out<<"Gain:"+gain<<" IntergerTime:"+inter_time<<endl
           <<QString("Pixel")<<QString(",Voltage")<<endl;

        for(int i=0;i<pixel.size();++i)
            out<<pixel.at(i)<<","<<voltage.at(i)<<endl;
    }else {
        return false;
    }

    QDir::setCurrent(root_dir.absolutePath()+"/../");

    return true;
}

bool FileSystem::save_file(const QList<double>& pixel, const QList<QList<double>>& voltages,const QString& gain, const QString& inter_time, const QString& ids)
{
    QDir file_dir = QDir(root_dir.absolutePath()+"/"+get_curr_date_dir()+"/"+ids);
    bool mkpath_ok = file_dir.mkpath(file_dir.absolutePath());
    if(!mkpath_ok&&!file_dir.exists()) return false;

    QDir::setCurrent(file_dir.absolutePath());

    QFile file(get_curr_time_fn()+ids+"_integration"+file_ext);
    if(file.open(QIODevice::WriteOnly | QIODevice::Text))
    {
        QTextStream out(&file);

        out<<"Gain:"+gain<<" IntergerTime:"+inter_time<<endl;
        out<<QString("Pixel");
        for(int i=1;i<=voltages.size();++i)
            out<<QString(",")<<QString("Vlotage%1").arg(i);
        out<<endl;

        for(int i=0;i<pixel.size();++i)
        {
            out<<pixel.at(i);
            for(int j=0;j<voltages.size();++j)
                out<<","<<voltages.at(j).at(i);
            out<<endl;
        }
    }else {
        return false;
    }

    QDir::setCurrent(root_dir.absolutePath()+"/../");

    return true;
}

QString FileSystem::get_curr_date_dir()
{
    QDateTime curr_dt = QDateTime::currentDateTime();
    return curr_dt.toString("yyyy-MM-dd");
}

QString FileSystem::get_curr_time_fn()//get current dt file name
{
    QDateTime curr_dt = QDateTime::currentDateTime();
    return curr_dt.toString("hh_mm_ss_");
}
